<template>
<div v-if="showPage" mgt2>
	<Row v-if="!commodity.shelved" :gutter="10">
		<Col :sm="{ span: 24, offset: 0 }" :md="{ span: 12, offset: 0 }">
			<p style="height:400px;" text-center>
				<background-image style="height:400px;max-width:400px;width:100%" :value=currentPicture></background-image>
			</p>
		</Col>
		<Col :sm="{ span: 24, offset: 0 }" :md="{ span: 12, offset: 0 }">
			<p sz4>
				{{commodity.commodityName}}
			</p>
			<Row type="flex" justify="start" align="middle" bg-gray5 mgt3>
				<Col span="24">
					<span gray3 lh4 pdx2 sz1>该商品已下柜，欢迎挑选其他商品！</span>
				</Col>
			</Row>
		</Col>
	</Row>
	<Row v-else :gutter="10">
		<Col :sm="{ span: 24, offset: 0 }" :md="{ span: 12, offset: 0 }">
			<p style="height:400px;" text-center>
				<background-image style="height:400px;max-width:400px;width:100%" :value=currentPicture></background-image>
			</p>
			<image-carousel item-width="80px" mgt3>
				<CarouselItem v-for="(item, i) in commodity.pictures" :key="i" pd1 h5>
					<background-image :value=item full bd-gray4 linkable 
						:bd-blue="item==currentPicture" @click="handleSetCurrentPicture(item)" />
				</CarouselItem>
			</image-carousel>
			<p text-center mgt3>
				<span style="vertical-align:auto">
					<Icon sz1 v-if="!commodity.isCollected" type="md-heart-outline" />
					<Icon sz1 v-else red type="md-heart" />
				</span>
				<span v-if="!commodity.isCollected" sz1 linkable @click="handleAddCollection">收藏商品</span>
				<span v-else sz1 linkable @click="handleCancelCollection">取消收藏</span>
				<span>（{{commodityCollectedCount}}人收藏）</span>
				<!-- <span pdx4 sz1 linkable><Icon type="md-share" />分享</span> -->
			</p>
		</Col>
		<Col :sm="{ span: 24, offset: 0 }" :md="{ span: 12, offset: 0 }">
			<p sz4>{{commodity.commodityName}}</p>
			<p mgt1><span v-if="commodity.isRecommended" sz0 bg-blue white pdy1 pdx2>推荐</span></p>
			<Row v-if="commodity.hasSalesPromotion" type="flex" justify="start" align="middle" bg-gray4 mgt3>
				<Col span="24" bg-red white pdx2 pdy1>
					<span>限时优惠</span>
					<span right>距离结束
						<span bg-gray1 pdx1>{{countDown.hours}}</span> : 
						<span bg-gray1 pdx1>{{countDown.minutes}}</span> : 
						<span bg-gray1 pdx1>{{countDown.seconds}}</span>
					</span>
				</Col>
				<Col span="4" sz1 pdx2>限时价</Col>
				<Col span="20">
					<p sz4 red lh4>￥{{formatPrice(commodity.price)}}</p>
				</Col>
			</Row>
			<Row v-else-if="commodity.discountable&&commodity.isForMember" type="flex" justify="start" align="middle" bg-gray4 mgt3>
				<Col span="4" sz1 pdx2>会员价</Col>
				<Col span="20">
					<span v-if="commodity.isEnabledShoppingOption&&commodity.shoppingOptionId==null" sz4 blue lh4>￥{{formatPrice(commodity.minPrice)}}~{{formatPrice(commodity.maxPrice)}}</span>
					<span v-else sz4 blue lh4>￥{{formatPrice(commodity.price)}}</span>
				</Col>
			</Row>
			<Row v-else type="flex" justify="start" align="middle" bg-gray4 mgt3>
				<Col span="4" sz1 pdx2>价格</Col>
				<Col span="20">
					<span v-if="commodity.isEnabledShoppingOption&&commodity.shoppingOptionId==null" sz4 blue lh4>￥{{formatPrice(commodity.minPrice)}}~{{formatPrice(commodity.maxPrice)}}</span>
					<span v-else sz4 blue lh4>￥{{formatPrice(commodity.price)}}</span>
					<span v-if="commodity.discountable&&!commodity.isForMember" blue sz0 pdx2>登录查看专属会员价</span>
				</Col>
			</Row>
			<Row v-if="commodity.hasSalesPromotion||(commodity.discountable&&commodity.isForMember)" type="flex" justify="start" align="middle" mgt3>
				<Col span="4" sz1 pdx2>原价</Col>
				<Col span="20">
					<s sz1>{{formatPrice(commodity.originalPrice)}}</s>
				</Col>
			</Row>
			<Row type="flex" justify="start" align="middle" mgt3>
				<Col span="4" sz1 pdx2>优惠券</Col>
				<Col span="20">
					<span v-for="(item, index) in coupons" :key="index" @click="handleReceiveCoupon(item.id)" white bg-orange pdx1 mgb1 mgr1 lh1 linkable-white>
						满{{item.minAmount}}减{{item.amount}}元
					</span>
					<router-link gray3 pdx2 lh1 linkable :to="{name:'coupon-center'}">更多 ></router-link>
				</Col>
			</Row>
			<Row type="flex" justify="start" align="middle" v-if="commodity.isEnabledShoppingOption" mgt3>
				<Col span="4" sz1 pdx2>选择规格</Col>
				<Col span="20">
					<RadioGroup type="button" v-model="model.shoppingOptionId" @on-change="handleGetRealCommodity">
						<Radio v-for="(item, index) in description.shoppingOptions" :key="index" :label="item.id" mgr1 mgt1>
							<span v-for="(value, key) in item.shoppingOptionParameters" :key="key" mgr1>{{value}}</span>
						</Radio>
					</RadioGroup>
				</Col>
			</Row>
			<Row type="flex" justify="start" align="middle" mgt3>
				<Col span="4" sz1 pdx2>数量</Col>
				<Col span="20">
					<count v-model="model.count" :min="commodity.minLimitCount" :max="commodity.maxLimitCount" :step="1" mgr2/>
					<!-- <span v-if="model.count <= commodity.minLimitCount" red mgr1>起购量为{{commodity.minLimitCount}}</span>
					<span v-if="model.count >= commodity.maxLimitCount" red>限购量为{{commodity.maxLimitCount}}</span> -->
				</Col>
			</Row>
			<Row type="flex" justify="start" align="middle" mgt3>
				<Col span="4" sz1 pdx2>库存</Col>
				<Col span="20">{{commodity.inventory}}件</Col>
			</Row>
			<p mgt4>
				<Button size="large" type="primary" @click="handleSettlement" mgr2 w7 :disabled="!canBug">立即购买</Button>
				<Button id="shopping-cart-btn" size="large" @click="handleAddCommodityToShoppingCart" :blue="canBug" :bd-blue="canBug" w7 :disabled="!canBug">加入购物车</Button>
			</p>
		</Col>
		<Col :span="isPhone?24:19" mgt4>
			<Tabs value="name1">
				<TabPane label="商品介绍" name="name1">
					<custom-spin :status="description.description?'success':'nodata'" style="height:30vh"></custom-spin>
					<div v-html="description.description"></div>
				</TabPane>
				<TabPane label="规格参数" name="name2" pd1>
					<custom-spin :status="Object.keys(description.specificationParameters).length?'success':'nodata'" style="height:30vh"></custom-spin>
					<table class="minitable" long>
						<tr v-for="(item, key) in description.specificationParameters" :key="key">
							<td w7>{{key}}</td>
							<td>{{item}}</td>
						</tr>
					</table>
				</TabPane>
				<TabPane :label="`商品评价(${commodityEvaluationCount})`" name="name3">
					<custom-spin :status="commodityEvaluationPage.totalCount?'success':'nodata'" style="height:30vh"></custom-spin>
					<commodity-evaluation :page="commodityEvaluationPage"></commodity-evaluation>
				</TabPane>
				<TabPane label="服务保证" name="name4">
					<custom-spin :status="commodityGuarantees.length?'success':'nodata'" style="height:30vh"></custom-spin>
					<div v-for="(item, index) in commodityGuarantees" :key="index" mgb3 bdb-gray5>
						<p sz2>{{item.displayName}}</p>
						<div v-html="item.description" gray3 mgt2 mgb2></div>
					</div>
				</TabPane>
			</Tabs>
		</Col>
		<Col v-if="!isPhone" :span=5 mgt4>
			<div class="bigtitle">
				<div class="bigtitle-title">为您推荐</div>
			</div>
			<div v-for="(item, index) in recommendedPage.items" :key="index" mgt2>
				<router-link gray1 linkable :to="{name:'commodity-detail', params: {id:item.commodityId}}" :title=item.commodityName>
					<BackgroundImage :value=item.picture style="width:100%;padding-bottom:100%;" bd-gray4>
						<p style="position:absolute;left:5px;bottom:5px" sz0>
							<span v-if="item.hasSalesPromotion" bg-red white pd1 mgr1>{{item.promotionName}}</span>
							<span v-if="item.isRecommended" bg-blue white pd1 mgr1>推荐</span>
						</p>
					</BackgroundImage>
					<p ellipsis long>{{item.commodityName}}</p>
					<p>
						<span v-if="!item.hasSalesPromotion&&item.isEnabledShoppingOption">￥{{item.minPrice}}~{{item.maxPrice}}</span>
						<span v-else>￥{{item.price}}</span>
					</p>
				</router-link>
			</div>
		</Col>
		<div id="shopping-cart-icon" style="position:fixed;opacity:0;" bd-circle bg-blue pdx1>
			<Icon type="ios-cart" white  />
		</div>
	</Row>
</div>
</template>

<script lang="ts">
import { Component, Vue,Inject, Prop,Watch } from 'vue-property-decorator';
import Jquery from 'jquery';
import AbpBase from '../../lib/abpbase';
import Commodity from '../../../../vue-common/store/entities/commodity'
import Page from '@common/models/Page'
import CommodityEvaluation from './commodity-evaluation'
import BackgroundImage from '@common/components/background-image'
import count from '../../components/common/count.vue'
import CustomSpin from '../../components/common/custom-spin.vue'
import ImageCarousel from '../../components/common/image-carousel.vue'

@Component({
	components: { CommodityEvaluation, BackgroundImage, count, CustomSpin, ImageCarousel }
})
export default class CommodityDetail extends AbpBase{
	model:any = {
		commodityId: 0,
		shoppingOptionId: null,
		count: 1
	}
	currentPicture:string = ""
	countDown = {
		hours: 0,
		minutes: 0,
		seconds: 0
	}
	commodity:any = {
	}
	description:any = {
		specificationParameters: {},
		shoppingOptions: []
	}
	commodityCollectedCount:Number = 0;
	commodityEvaluationPage:Page = new Page('/api/services/app/OrderEvaluate/GetCommodityEvaluates');
	couponPage:Page = new Page('/api/services/app/Coupon/Search');
	recommendedPage:Page = new Page('/api/services/app/Home/GetCommodityRecommendeds').pageSize(2);
	get coupons() {
		return this.couponPage.items;
	}
	get canBug() {
		if(!this.commodity.commodityId) return false;
		if(this.commodity.inventory == 0) return false;
		if(this.model.count <= 0) return false;
		if(this.commodity.minLimitCount <= 0) return false;
		if(this.commodity.isEnabledShoppingOption) {
			if(this.model.shoppingOptionId != null) {
				return true;
			}else {
				return false;
			}
		}else {
			return true;
		}
	}
	get commodityEvaluationCount() {
		var totalCount = this.commodityEvaluationPage.totalCount;
		if(totalCount < 10000) {
			return totalCount;
		}else {
			var temp= Math.floor(totalCount / 10000);
			return `${temp}万+`;
		}
	}
	calaCountDown() {
		if(!this.commodity.hasSalesPromotion) return;

		var interval = setInterval( () => {
			var now = Date.now();
			var end = new Date(this.commodity.promotionEndTime).getTime();
			var temp = Math.floor((end - now) / 1000);

			if(temp <= 0) {
				this.commodity.hasSalesPromotion = false;
				clearInterval(interval);
			}

			this.countDown.hours = Math.floor(temp / 3600);
			this.countDown.minutes = Math.floor(temp / 60) % 60;
			this.countDown.seconds = temp % 60;
		}, 1000);
	} 
	handleSetCurrentPicture(picture){
		this.currentPicture = picture;
	}
	addCommodityToShoppingCartAnimate() {
		var btn = document.getElementById("shopping-cart-btn");
		var top = document.getElementById("shopping-cart-top");
		var icon = document.getElementById("shopping-cart-icon");
		var btnRect = btn.getClientRects();
		var topRect = top.getClientRects();
		icon.style.top = btnRect[0].y + 5 + "px";
		icon.style.left = btnRect[0].x + 50 + "px";
		icon.style.opacity = "1";
		Jquery(icon).animate({
			top: topRect[0].y + "px", 
			left: topRect[0].x + "px",
			opacity: 0.5
		}, "slow", "swing");
		Jquery(icon).animate({
			opacity: 0
		}, "fast", "swing");
	}
	get commodityGuarantees() {
		return this.$store.state.setting.settings.commodityGuarantees;
	}
	async handleAddCommodityToShoppingCart() {
		if(!this.isLogined) {
			this.$router.push({
				name: 'login'
			});
			return;
		}
		this.addCommodityToShoppingCartAnimate();
		var response = await this.post('ShoppingCart/AddCommodityToShoppingCart', this.model);
		await this.$store.dispatch({
			type:'shoppingcart/getAll'
		});
	}
	async handleGetCommodityCollectedCount() {
		var response = await this.get('Collection/GetCommodityCollectedCount', { commodityId: this.model.commodityId });
		if(response.success) {
			this.commodityCollectedCount = response.result;
		}
	}
	async handleAddCollection() {
		var response = await this.post('Collection/Add', this.model);
		if(response.success) {
			await this.handleGetCommodityCollectedCount();
			this.commodity.isCollected = true;
		}
	}
	async handleCancelCollection() {
		var response = await this.post('Collection/Cancel', this.model);
		if(response.success) {
			await this.handleGetCommodityCollectedCount();
			this.commodity.isCollected = false;
		}
	}
	async handleGetRealCommodity() {
		var temp:any = {};
		var response = await this.get("Commodity/GetShelved", this.model);
		if(response.success) {
			var elem = response.result;
			elem.maxLimitCount = Math.min(elem.maxLimitCount, elem.inventory);
			elem.minLimitCount = Math.min(elem.minLimitCount, elem.maxLimitCount);
			this.commodity = elem;
		}
		this.handleSetCurrentPicture(this.commodity.picture);
	}
	async handleGetCommodityDescription() {
		var response = await this.get('Commodity/GetShelvedDescription', { id: this.model.commodityId });
		if(response.success) {
			this.description.description = response.result.description;
			this.description.specificationParameters = response.result.specificationParameters;
			this.description.shoppingOptions = response.result.shoppingOptions;
		}
	}
	async handleGetCouponsForCommodity() {
		this.couponPage.getData();
	}
	async handleReceiveCoupon(id:Number){
		var response = await this.post('Coupon/MemberReceiveCoupon', { id: id });
		if(response.success) {
			this.success('领取成功！');
		}
	}
	handleSettlement() {
		if(!this.isLogined) {
			this.$router.push({
				name: 'login'
			});
			return;
		}
		var items = [this.model];
		this.$router.push({
			name: 'submit-order',
			query: {
				model: JSON.stringify({
					items: items,
					isFromShoppingCart: false
				})
			}
		});
	}
	async init() {
		this.model.commodityId = this.$route.params.id;
		this.model.shoppingOptionId = null;
		this.model.count = 1;

		this.commodityEvaluationPage.action_data.commodityId = this.model.commodityId;
		this.couponPage.action_data.commodityId = this.model.commodityId;
		this.couponPage.action_data.status = 'ongoing';

		this.showPage = false;
		await this.handleGetRealCommodity();
		this.showPage = true;

		if(this.commodity.shelved) {
			await this.handleGetCommodityDescription();
			await this.handleGetCommodityCollectedCount();
			await this.handleGetCouponsForCommodity();
		}

		this.calaCountDown();
	}
	async created() {
		await this.init();

		this.recommendedPage.getData();
	}
	@Watch('$route')
	async handleRouteChange() {
		await this.init();
	}
}
</script>